#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "znet.h"


int on_sess_open(zsess_t *s)
{
    printf("[%s:%d] online.\n", s->addr, s->port);
    return 0;
}

void on_sess_recv(zsess_t *s)
{
    char buf[1024] = {0};
    int ret = znet_recv(s->sock, buf, 1024);
    printf("recv[%d]: %s\n", ret, buf);
}

void on_sess_exit(zsess_t *s)
{
    printf("[%s:%d] offline.\n", s->addr, s->port);
}

void on_server_launch(int port)
{
    printf("server port: %d\n", port);
}

int server_launch(int port)
{
    znet_t srv = {
        .port = port,
        .bufsize = 1024,
        .on_launch = on_server_launch,
        .on_open = on_sess_open,
        .on_recv = on_sess_recv,
        .on_exit = on_sess_exit,
    };

    return znet_launch(&srv, ZNET_SERVER);
}

int client_launch(char *addr, int port, char *data)
{
    znet_t cli = {
        .addr = addr,
        .port = port,
    };

    if (znet_launch(&cli, ZNET_CLIENT) !=0) {
        printf("client init error\n");
        return -1;
    }

    return znet_send(cli.sock, data, strlen(data));
}

int main(int argc, char *argv[])
{
#ifdef SERVER
    if (argc != 2) {
        printf("server <port>\n");
        return -1;
    }
    server_launch(atoi(argv[1]));
#endif

#ifdef CLIENT
    if (argc != 4) {
        printf("client <ip> <port> <data>\n");
        return -1;
    }
    client_launch(argv[1], atoi(argv[2]), argv[3]);
#endif
    return 0;
}
